<?php
declare (strict_types=1);

namespace app\mall\logic\product\admin;

use app\common\exception\LogicException;
use app\mall\model\product\admin\Product as ProductModel;
use Exception;
use think\db\exception\DbException;
use think\Model;
use think\Paginator;

/**
 * 后台商品逻辑层
 */
class Product extends ProductModel
{

    /**
     * getList
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/18
     *
     * @param array $map
     * @return Paginator
     * @throws DbException
     */
    public function getList(array $map = []): Paginator
    {
        return $this->with(['cover_url'])->where($map)->order('update_time', 'DESC')->paginate(static::getListRows());
    }

    /**
     * 编辑指定字段
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/25
     *
     * @param $id
     * @param $field
     * @param $value
     * @return Product|array|Model
     */
    public function editField($id, $field, $value)
    {
        // 信息
        $data = $this->findOrFail($id);

        $data->$field = $value;

        if (!$data->save()) throw new LogicException('更新失败');

        // 返回值
        return $data;
    }

    /**
     * 新建商品
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/28
     *
     * @param array $data
     */
    public function createProduct(array $data)
    {
        // 验证数据
        $this->getValidate()->scene('create')->failException()->check($data);

        $data['mhm_id']           = request()->mhm_id;
        $data['category']         = $data['cates'];
        $data['fullcategorypath'] = $data['cates'];
        $this->startTrans();
        try {
            $re = $this::create($data);
            if ($re->isEmpty()) throw new LogicException('新建失败');
            /** @var ProductSwiper $swiper */
            $swiper = app(ProductSwiper::class);
            $swiper->addSwipers($re->id, $data['swiper']);
            $this->commit();
        } catch (LogicException $e) {
            $this->rollback();
            // throw new LogicException($e->getMessage());
            throw new LogicException('编辑失败');
        }
    }

    /**
     * 编辑商品
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/28
     *
     * @param int $id
     * @param     $param
     */
    public function editProduct(int $id, $param)
    {
        $data = $this->with(['swiper_list'])->findOrEmpty($id);
        // 取得验证器
        $this->getValidate()->scene('create')->failException()->check($param);

        $data->title            = $param['title'];
        $data->fullcategorypath = $param['cates'];
        $data->category         = $param['cates'];
        $data->cover            = $param['cover'];
        $data->info             = $param['info'];
        $data->status           = $param['status'];
        $data->is_recommend     = $param['is_recommend'];
        $data->best_sort        = $param['best_sort'];
        $data->scribing_price   = $param['scribing_price'];
        $data->cash_price       = $param['cash_price'];
        $data->credit_price     = $param['credit_price'];
        $data->stock_num        = $param['stock_num'];
        $data->fictitious       = $param['fictitious'];
        $data->carriage         = $param['carriage'];

        $this->startTrans();
        try {
            if (!$data->save()) throw new LogicException('编辑失败');
            $swipers = array_column($data->swiper_list->toArray(), 'attach_id');
            $inst    = array_intersect($swipers, $param['swiper']);
            $del     = array_diff($swipers, $inst);
            $add     = array_diff($param['swiper'], $inst);

            if (count($del) || count($add)) {
                // 更新轮播图
                /** @var ProductSwiper $swiper */
                $swiper = app(ProductSwiper::class);
                count($del) && $swiper->delSwiperByAttachIds($id, $del);
                count($add) && $swiper->addSwipers($id, $add);
            }
            $this->commit();
        } catch (LogicException $e) {
            $this->rollback();
            // throw new LogicException($e->getMessage());
            throw new LogicException('编辑失败');
        }
    }

    /**
     * 批量下架
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/28
     *
     * @param array $ids
     * @throws Exception
     */
    public function disableProducts(array $ids)
    {
        $prod = new Product();
        $save = [];
        foreach ($ids as $id) {
            $save[] = ['id' => $id, 'status' => 0];
        }
        $res = $prod->saveAll($save);
        if ($res->isEmpty()) throw new LogicException('禁用失败');
    }

    /**
     * 批量更新数据
     *
     * @param array  $ids
     * @param string $field
     * @param        $value
     */
    public function batchUpdated(array $ids, string $field, $value)
    {
        $ret = ProductModel::update([$field => $value], [['id', 'in', $ids]]);
        if (!$ret) {
            throw new LogicException('批量操作失败');
        }
    }

    /**
     * 删除商品
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/28
     *
     * @param int $id
     */
    public function deleteProduct(int $id): void
    {
        // 信息
        $data = $this->findOrFail($id);
        if (!$data->delete()) throw new LogicException('删除失败');
    }

    /**
     * 批量删除
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/28
     *
     * @param string $ids
     */
    public function deleteProducts(string $ids): void
    {
        if (!Product::destroy($ids)) throw new LogicException('删除失败');
    }

}
